/**
 * 取消重复请求
 *
 */
import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import router from '../router/index'
import serverUrl from '../config/url'

let v = new Vue()

axios.defaults.timeout = 50000
axios.defaults.baseURL = serverUrl
axios.defaults.withCredentials = true

let pending = []
let CancelToken = axios.CancelToken

let removePending = ever => {
  for (const p in pending) {
    if (pending[p].u === `${ever.url}&${ever.method}`) {
      pending[p].f('Cancel')
      pending.splice(p, 1)
    }
  }
}

axios.interceptors.request.use(
  config => {
    removePending(config)

    config.cancelToken = new CancelToken(c => {
      pending.push({
        u: `${config.url}&${config.method}`,
        f: c
      })
    })
    /** 通过 qs 对 FormData 请求参数改造 */
    // config.url = config.url + `&sys_rnd=${Math.random()}`

    // 对于查询条件进行改造
    if (config.data && config.data.sys_search) {
      let cacheSysSearch = config.data.sys_search
      let sysSearch = []
      for (const key in cacheSysSearch) {
        if (cacheSysSearch.hasOwnProperty(key)) {
          if ((typeof (cacheSysSearch[key]) === 'string' && cacheSysSearch[key].length === 0) || !cacheSysSearch[key]) {} else {
            sysSearch.push({
              name: key,
              value: cacheSysSearch[key],
              pattern: 'like'
            })
          }
        }
      }
      config.data.sys_search = JSON.stringify(sysSearch)
    }

    config.data = qs.stringify(config.data)

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  resp => {
    removePending(resp.config)
    let respData = resp.data
    /** 由于请求返回的数据格式不一致，只能对 respData.success 进行判断 */
    if (typeof (respData.success) === 'boolean') {
      if (!respData.success && respData.msg) {
        v.$message.error(respData.msg)
        return Promise.reject(respData)
      } else {
        return respData
      }
    } else {
      return respData
    }
  },
  error => {
    if (error.message && error.message === 'Cancel') {
      return Promise.reject(error)
    } else {
      let errResp = error.response
      if (errResp && errResp.data) {
        if (errResp.status === 405) {
          router.replace({
            name: 'login'
          })
          v.$message.error(errResp.data)
        } else {
          v.$message.error(errResp.data)
        }
        return Promise.reject(error)
      }

      v.$message.error(error.message)
      return Promise.reject(error)
    }
  }
)

export default axios
